package com.lp.batch.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.lp.batch.domain.Node;
import com.lp.batch.service.TemplateService;

/**
 * An implementation of a TemplateService that uses Velocity to generate
 * HTML pages.
 * 
 * @author Zainul Franciscus
 *
 */
@Service("velocityService")
public class VelocityServiceImpl implements TemplateService {

	/**
	 * The name of the default Velocity template for this application
	 */
	private static final String DEFAULT_TEMPLATE = "layout.vm";
	/**
	 * Used to merge destination information to the template
	 */
	@Autowired
	private VelocityEngine velocityEngine;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lp.batch.service.impl.TemplateService#createPage(java.util.Map)
	 */
	public String mergeModelToTemplate(Map<String, Node> model) {

		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, DEFAULT_TEMPLATE, model);

	}

	/*
	 * Write an HTML page that records information about the node in the
	 * specified directory. The name of the HTML page will be the node's atlas
	 * node id.
	 * 
	 * @see
	 * com.lp.batch.service.TemplateService#createAPageFromTemplate(java.lang
	 * .String, com.lp.batch.domain.Node)
	 */
	public void createAPageFromTemplate(String directory, Node node) throws IOException {

		Map<String, Node> model = new HashMap<String, Node>();
		model.put("node", node);

		String fileName = String.valueOf(node.getAtlasNodeId()) + ".html";

		File file = new File(directory, fileName);
		FileUtils.writeStringToFile(file, mergeModelToTemplate(model));

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lp.batch.service.TemplateService#createStyleSheet(java.lang.String)
	 */
	public void createStyleSheet(String directory, File stylesheet) throws IOException {

		File dir = new File(directory + "/static/all.css");
		FileUtils.copyFile(stylesheet, dir);

	}

}
